<script>
import {
  defineComponent,
  computed,
  unref,
  reactive,
  toRaw,
  watch,
  onUpdated,
  ref,
} from 'vue'
import * as Antd from 'ant-design-vue'

export default defineComponent({
  props: {
    options: {
      type: Array,
      default: () => {
        return []
      },
    },
    emptyLable: {
      type: String,
      default: '全部',
    },
  },
  setup(props, context) {
    let _options = reactive({ data: toRaw(props.options) })

    let options = computed({
      set: (value) => {
        //  props.options;
        _options.data = value
      },

      get: () => {
        // props.options;
        return _options.data
      },
    })

    watch(
      () => {
        return props.options
      },
      (value, preValue) => {
        options.value = toRaw(value)
      },
      { deep: true }
    )

    watch(
      () => {
        return context.attrs.uiAttr.value
      },
      (value, prevalue) => {
        if (value == null) {
          _options.data = _options.data.filter((x) => {
            return x.value != null
          })
        } else {
          if (
            _options.data.filter((x) => {
              return x.value == null
            }).length == 0
          ) {
            _options.data.unshift({ value: null, label: props.emptyLable })
          }
        }
      },
      {
        deep: true,
      }
    )

    let onChange = (value, __option) => {
      let hasNull = unref(options).filter((x) => x.value == null).length == 0

      if (value != null && hasNull) {
        options.value = [
          // { value: null, label: props.emptyLable },
          ...toRaw(props.options),
        ]
      } else if (value == null) {
        options.value = toRaw(props.options) // unref(options).filter((x) => x.value != null);
      }

      context.emit('change', { value: value, option: __option })
    }

    return { context, options, onChange, props }
  },
  render() {
    return (
      <>
        <Antd.Select
          {...this.context.attrs.uiAttr}
          options={this.options}
          onChange={this.onChange}
          v-slots={this.context.attrs.uiAttr.slots}
        ></Antd.Select>
      </>
    )
  },
})
</script>
